#!/usr/bin/perl
#
# Delete an User record
# The presumption is that this user has been checked and found
# to own nothing at all, and its address is illegal, so it's
# worthless to keep around.
#
use FileTable;
use Fcntl;
use Counter::CGI;
use CGI::Carp;
use ErrorForm;

$] > 5.008 && binmode(STDOUT, ":utf8"); # set web page output to utf-8
$q = new Counter::CGI;
$key = $q->param('key');

$file = FileTable::open("db/users", O_RDWR);
# Check for linked data
$persons = FileTable::open("db/persons");
$friends = FileTable::open("db/friends");
$machines = FileTable::open("db/machines");
$usergroups = FileTable::open("db/usergroups");

$pers = $persons->get($key);
@mach = $machines->select("owner = ?", $key);
$mcount = $#mach + 1;
@fri = $friends->select("owner = ?", $key);
$frcount = $#fri + 1;
@ug = $usergroups->select("owner = ?", $key);
$ugcount = $#ug +1;
if ($mcount | $frcount | $ugcount) {
    errorForm("Key $key owns $mcount machines, $frcount friends, and $ugcount usergroups");
}


warn "Deleting record $key\n";
$rec = $file->get($key);

if (!$rec) {
    errorForm("Key $key does not exist");
}
$rec->delete();

print <<EoF;
content-type: text/html; charset="utf-8"

<html>
<head>
<title>Linux Counter user record deleted</title>
</head>
<body bgcolor=white>
<h1>User record $key deleted</h1>
Hope that's OK
</body>
</html>
EoF
